package com.yupi.project.filters;

import com.yupi.project.model.AuthenticatorResult;
import com.yupi.project.security.DefaultApiAuthenticator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j(topic = "ApiAuthenticatorFilter")
public class ApiAuthenticatorFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 创建责任链对象，使用策略模式+责任链模式对请求进行多重校验
        DefaultApiAuthenticator defaultApiAuthenticator = new DefaultApiAuthenticator();
        AuthenticatorResult result = defaultApiAuthenticator.auth(exchange);
        if(!result.isSuccess()){
            return Mono.error(new HttpServerErrorException(HttpStatus.METHOD_NOT_ALLOWED, result.getErrorMsg()));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
